﻿using DotNetty.Wraper;
using Examples.Common;
using Microsoft.Extensions.Logging;
using System;
using System.Text;
using System.Threading.Tasks;

namespace TcpSocket.Client
{
    class Program
    {
        static async Task Main(string[] args)
        {
            ILogger _logger = new CNative.Logging.ConfigLogger();
            var option = new ClientOption();
            option.SeverIp = Examples.Common.ClientSettings.Host.ToString();
            option.Port = Examples.Common.ClientSettings.Port;
            option.UseLibuv = Examples.Common.ClientSettings.UseLibuv;
            if (Examples.Common.ServerSettings.IsSsl)
            {
                option.Certificate = System.IO.Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx");
                option.CertificatePassword = "password";
            }
            var theClientBuild = SocketBuilderFactory.GetTcpSocketClientBuilder(option)
                .OnChannelRegistered((client, channel) =>
                {
                    _logger.LogDebug("OnChannelRegistered: " + channel.Id);
                })
                .OnChannelRegistered((client, channel) =>
                {
                    _logger.LogDebug("OnChannelRegistered: " + channel.Id);
                })
                .OnClientStarted(client =>
                {
                    _logger.LogInformation($"客户端启动");
                    client.Send("Hello world" + DateTime.Now);
                })
                .OnClientClose(client =>
                {
                    _logger.LogInformation($"客户端关闭");
                })
                .OnException(ex =>
                {
                    _logger.LogError($"异常:{ex.Message}");
                })
                .OnRecieve((client, bytes) =>
                {
                    _logger.LogInformation($"客户端:收到数据:{Encoding.UTF8.GetString(bytes)}");
                    client.Send("Hello world " + DateTime.Now);
                })
                .OnSend((client, bytes) =>
                {
                    _logger.LogInformation($"客户端:发送数据:{Encoding.UTF8.GetString(bytes)}");
                });

            var theClient = await theClientBuild .BuildAsync((pipeline) =>
            {
                pipeline.AddLast("framing-enc", new DotNetty.Codecs.LengthFieldPrepender(2));
                pipeline.AddLast("framing-dec", new DotNetty.Codecs.LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
            });
            Console.ReadLine();

            theClient?.Close();
        }
    }
}